"""文档解析工具 - 支持PDF、Word等文档格式的读取和解析。"""

import os
from typing import Dict, Any, List
from langchain_core.tools import tool
from langchain_community.document_loaders import (
    PyPDFLoader,
    Docx2txtLoader,
    TextLoader,
    UnstructuredPowerPointLoader
)
from langchain.text_splitter import RecursiveCharacterTextSplitter


@tool
def read_document(file_path: str) -> Dict[str, Any]:
    """读取文档内容，支持PDF、Word、TXT、PPT等格式。
    
    Args:
        file_path: 文档文件路径
        
    Returns:
        包含文档内容和元数据的字典
    """
    try:
        if not os.path.exists(file_path):
            return {"error": f"文件不存在: {file_path}"}
        
        # 获取文件扩展名
        file_ext = os.path.splitext(file_path)[1].lower()
        
        # 根据文件类型选择合适的加载器
        if file_ext == '.pdf':
            loader = PyPDFLoader(file_path)
        elif file_ext in ['.docx', '.doc']:
            loader = Docx2txtLoader(file_path)
        elif file_ext == '.txt':
            loader = TextLoader(file_path, encoding='utf-8')
        elif file_ext in ['.pptx', '.ppt']:
            loader = UnstructuredPowerPointLoader(file_path)
        else:
            return {"error": f"不支持的文件格式: {file_ext}"}
        
        # 加载文档
        documents = loader.load()
        
        # 提取内容和元数据
        content = "\n".join([doc.page_content for doc in documents])
        metadata = {
            "file_path": file_path,
            "file_type": file_ext,
            "page_count": len(documents),
            "char_count": len(content),
            "word_count": len(content.split())
        }
        
        return {
            "content": content,
            "metadata": metadata,
            "documents": documents
        }
        
    except Exception as e:
        return {"error": f"读取文档失败: {str(e)}"}


@tool
def split_document(content: str, chunk_size: int = 1000, chunk_overlap: int = 200) -> List[str]:
    """将文档内容分割成较小的块。
    
    Args:
        content: 文档内容
        chunk_size: 每个块的大小
        chunk_overlap: 块之间的重叠大小
        
    Returns:
        分割后的文本块列表
    """
    try:
        text_splitter = RecursiveCharacterTextSplitter(
            chunk_size=chunk_size,
            chunk_overlap=chunk_overlap,
            length_function=len,
        )
        
        chunks = text_splitter.split_text(content)
        return chunks
        
    except Exception as e:
        return [f"分割文档失败: {str(e)}"]


@tool
def analyze_document_structure(content: str) -> Dict[str, Any]:
    """分析文档结构，提取标题、段落等信息。
    
    Args:
        content: 文档内容
        
    Returns:
        文档结构分析结果
    """
    try:
        lines = content.split('\n')
        
        # 简单的结构分析
        structure = {
            "total_lines": len(lines),
            "non_empty_lines": len([line for line in lines if line.strip()]),
            "potential_headings": [],
            "paragraphs": [],
            "summary": ""
        }
        
        current_paragraph = []
        
        for line in lines:
            line = line.strip()
            if not line:
                if current_paragraph:
                    structure["paragraphs"].append(" ".join(current_paragraph))
                    current_paragraph = []
                continue
            
            # 检测可能的标题（短行、全大写或以数字开头）
            if (len(line) < 50 and 
                (line.isupper() or 
                 line[0].isdigit() or 
                 any(keyword in line.lower() for keyword in ['第', '章', 'chapter', '部分']))):
                structure["potential_headings"].append(line)
            
            current_paragraph.append(line)
        
        # 添加最后一个段落
        if current_paragraph:
            structure["paragraphs"].append(" ".join(current_paragraph))
        
        # 生成简单摘要（前200个字符）
        structure["summary"] = content[:200] + "..." if len(content) > 200 else content
        
        return structure
        
    except Exception as e:
        return {"error": f"分析文档结构失败: {str(e)}"}


# 导出工具列表
document_tools = [read_document, split_document, analyze_document_structure]